<template>
  <div class="home">
    <!-- Hero Section with animation -->
    <section class="hero-section relative overflow-hidden bg-gradient-to-br from-blue-50 to-indigo-100 py-16" ref="heroRef">
      <div class="container mx-auto px-4">
        <div class="text-center">
          <h1 class="hero-title text-4xl md:text-6xl font-bold text-gray-800 mb-6">
            专业药品平台
          </h1>
          <p class="hero-subtitle text-lg md:text-xl text-gray-600 mb-8 max-w-2xl mx-auto">
            为您提供安全、可靠的药品服务，守护您和家人的健康
          </p>
          <div class="hero-cta">
            <button class="bg-red-500 hover:bg-red-600 text-white px-8 py-3 rounded-lg font-medium transition-colors">
              立即购买
            </button>
          </div>
        </div>
      </div>
      
      <!-- Floating medical elements -->
      <div class="floating-elements absolute inset-0 pointer-events-none">
        <div class="floating-pill absolute top-20 left-10 w-6 h-12 bg-gradient-to-b from-red-400 to-red-600 rounded-full" ref="pill1"></div>
        <div class="floating-pill absolute top-40 right-20 w-8 h-16 bg-gradient-to-b from-blue-400 to-blue-600 rounded-full" ref="pill2"></div>
        <div class="floating-cross absolute bottom-32 left-20 w-8 h-8" ref="cross1">
          <div class="w-full h-1 bg-green-500 absolute top-1/2 transform -translate-y-1/2"></div>
          <div class="w-1 h-full bg-green-500 absolute left-1/2 transform -translate-x-1/2"></div>
        </div>
      </div>
    </section>

    <div class="container mx-auto px-4 py-8">
      <!-- Featured Products -->
      <section 
        v-if="featuredProduct && products.length > 0"
        class="product-section mb-16"
        ref="featuredRef"
        data-type="featured"
      >
        <div class="section-header mb-8">
          <h2 class="text-2xl md:text-3xl font-bold text-gray-800 mb-2">精选商城</h2>
          <div class="w-16 h-1 bg-red-500 rounded"></div>
        </div>
        <ProductShowcase
          title="精选商品"
          :featured-product="featuredProduct"
          :products="products.slice(0, 3)"
        />
      </section>

      <!-- New Arrivals -->
      <section 
        v-if="newArrivals.length > 0"
        class="product-section mb-16"
        ref="newArrivalsRef"
        data-type="new-arrivals"
      >
        <div class="section-header mb-8">
          <h2 class="text-2xl md:text-3xl font-bold text-gray-800 mb-2">新品上架</h2>
          <div class="w-16 h-1 bg-blue-500 rounded"></div>
        </div>
        <ProductShowcase
          title="新品上架"
          :featured-product="newArrivals[0]"
          :products="newArrivals.slice(1, 4)"
        />
      </section>

      <!-- Hot Sales -->
      <section 
        v-if="hotSales.length > 0"
        class="product-section mb-16"
        ref="hotSalesRef"
        data-type="hot-sales"
      >
        <div class="section-header mb-8">
          <h2 class="text-2xl md:text-3xl font-bold text-gray-800 mb-2">热销商品</h2>
          <div class="w-16 h-1 bg-green-500 rounded"></div>
        </div>
        <ProductShowcase
          title="热销商品"
          :featured-product="hotSales[0]"
          :products="hotSales.slice(1, 4)"
        />
      </section>
    </div>

    <!-- Loading overlay -->
    <div v-if="isLoading" class="fixed inset-0 bg-white bg-opacity-90 flex items-center justify-center z-50">
      <MedicalLoader size="large" text="加载药品信息zh.." />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import ProductShowcase from './components/ProductShowcase.vue'
import MedicalLoader from '@/components/animations/MedicalLoader.vue'
import { getProducts } from '@/api/product'
import type { DisplayGoods } from '@/views/HomeView.vue'
import { animations, animationUtils } from '@/components/animations/GSAPAnimations'

interface Product {
  id: number
  name: string
  desc?: string
  price: string
  originalPrice?: string
  imgUrl: string
  specification?: string
  salesVolume?: number
  stockLevel?: number
  expiryDate?: string
  manufacturer?: string
}

function productToDisplayGoods(product: Product): DisplayGoods {
  return {
    // 基础字段
    id: product.id,
    createTime: '',
    updateTime: '',
    tenantId: null,
    typeId: 0,
    title: product.name,
    subTitle: product.desc ?? '',
    mainPic: product.imgUrl ?? '',
    pics: '',
    price: product.price,
    sold: product.salesVolume ?? 0,
    content: '',
    status: 1,
    sortNum: 0,
    goodsId: '',
    entId: '',
    goodsCode: '',
    oracleGoodsName: '',
    goodsSpec: product.specification ?? '',
    manufacturer: product.manufacturer ?? '',
    unit: '',
    approvalNo: '',
    formula: '',
    midpack: 0,
    qty: '',
    planCate: '',
    logogram: '',
    wholLimtNum: 0,
    storNum: String(product.stockLevel ?? 0),
    isMidpackSaleDisabled: 0,
    gCategory: '',
    qCategory: '',
    oracleIsHidden: 0,
    isPres: 0,
    attribute: '',
    // DisplayGoods 扩展字段
    name: product.name,
    imgUrl: product.imgUrl ?? '',
    specification: product.specification ?? '',
    salesVolume: product.salesVolume ?? 0,
    stockLevel: product.stockLevel ?? 0,
    expiryDate: product.expiryDate,
    category: undefined,
    typeName: '',
    visitCount: 0,
    lastVisitTime: '',
    originalPrice: product.originalPrice
  }
}

// Template refs
const heroRef = ref<HTMLElement | null>(null)
const featuredRef = ref<HTMLElement | null>(null)
const newArrivalsRef = ref<HTMLElement | null>(null)
const hotSalesRef = ref<HTMLElement | null>(null)
const pill1 = ref<HTMLElement | null>(null)
const pill2 = ref<HTMLElement | null>(null)
const cross1 = ref<HTMLElement | null>(null)

// Data
const products = ref<DisplayGoods[]>([])
const featuredProduct = ref<DisplayGoods | null>(null)
const newArrivals = ref<DisplayGoods[]>([])
const hotSales = ref<DisplayGoods[]>([])
const isLoading = ref(true)

// Animation instances
let heroAnimations: gsap.core.Timeline[] = []
let sectionAnimations: gsap.core.Tween[] = []
let floatingAnimations: gsap.core.Tween[] = []

const fetchProducts = async () => {
  try {
    const response = await getProducts()
    if (response.data && response.data.length > 0) {
      const displayGoodsList = response.data.map(productToDisplayGoods)
      products.value = displayGoodsList.slice(0, 10)
      featuredProduct.value = products.value[0] ?? null
      newArrivals.value = [...displayGoodsList].sort((a, b) => b.id - a.id).slice(0, 4)
      hotSales.value = [...displayGoodsList].sort((a, b) => (b.salesVolume ?? 0) - (a.salesVolume ?? 0)).slice(0, 4)
    }
  } catch (error) {
    console.error('Failed to fetch products:', error)
  } finally {
    isLoading.value = false
  }
}

function setupHeroAnimations() {
  if (!heroRef.value) return

  const heroTimeline = animationUtils.createPageTimeline()
  
  // Title animation
  const title = heroRef.value.querySelector('.hero-title')
  if (title) {
    heroTimeline.from(title, {
      opacity: 0,
      y: 50,
      scale: 0.8,
      duration: 1,
      ease: "power3.out"
    })
  }

  // Subtitle animation
  const subtitle = heroRef.value.querySelector('.hero-subtitle')
  if (subtitle) {
    heroTimeline.from(subtitle, {
      opacity: 0,
      y: 30,
      duration: 0.8,
      ease: "power2.out"
    }, "-=0.5")
  }

  // CTA animation
  const cta = heroRef.value.querySelector('.hero-cta')
  if (cta) {
    heroTimeline.from(cta, {
      opacity: 0,
      scale: 0.8,
      duration: 0.6,
      ease: "back.out(1.7)"
    }, "-=0.3")
  }

  heroAnimations.push(heroTimeline)
}

function setupFloatingAnimations() {
  // Floating pills
  if (pill1.value) {
    const anim1 = animations.floatingAnimation(pill1.value)
    floatingAnimations.push(anim1)
  }
  
  if (pill2.value) {
    const anim2 = animations.floatingAnimation(pill2.value)
    floatingAnimations.push(anim2)
  }

  // Floating cross
  if (cross1.value) {
    const anim3 = animations.floatingAnimation(cross1.value)
    floatingAnimations.push(anim3)
  }
}

function setupSectionAnimations() {
  // Setup scroll-triggered animations for each section
  const sections = [featuredRef.value, newArrivalsRef.value, hotSalesRef.value]
  
  sections.forEach((section) => {
    if (section) {
      const animation = animations.scrollTriggerFadeIn(section, {
        start: "top 80%",
        end: "bottom 20%"
      })
      sectionAnimations.push(animation)
    }
  })
}

onMounted(async () => {
  await fetchProducts()
  
  nextTick(() => {
    setupHeroAnimations()
    setupFloatingAnimations()
    setupSectionAnimations()
  })
})

onUnmounted(() => {
  // Cleanup all animations
  heroAnimations.forEach(anim => animationUtils.cleanup(anim))
  sectionAnimations.forEach(anim => animationUtils.cleanup(anim))
  floatingAnimations.forEach(anim => animationUtils.cleanup(anim))
})
</script>

<style scoped>
.hero-section {
  min-height: 60vh;
  position: relative;
}

.floating-elements {
  overflow: hidden;
}

.floating-pill {
  filter: blur(0.5px);
  opacity: 0.7;
}

.floating-cross {
  opacity: 0.6;
}

.product-section {
  opacity: 0;
  transform: translateY(30px);
}

.section-header h2 {
  position: relative;
  display: inline-block;
}

.section-header h2::after {
  content: '';
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 0;
  height: 2px;
  background: linear-gradient(90deg, #dc2626, #f59e0b);
  transition: width 0.3s ease;
}

.section-header:hover h2::after {
  width: 100%;
}

/* Responsive design */
@media (max-width: 768px) {
  .hero-section {
    min-height: 50vh;
    padding: 8rem 0;
  }
  
  .floating-elements {
    display: none;
  }
}
</style> 
